<template>
  <div class="container">
    <div class="app-container">
      <!-- 卡片视图部分 -->
      <el-card class="box-card" shadow="never">
        <!-- 表单区域 -->
        <el-form :inline="true" :model="companyForm" class="demo-form-inline">
          <el-row :gutter="20">
            <el-col :span="5">
              <el-form-item label="标签名称：">
                <el-input
                  v-model.trim="companyForm.tags"
                  placeholder="请输入"
                  clearable
                  @keyup.enter.native="searchForm"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="城市：">
                <el-select
                  v-model="companyForm.province"
                  @change="getCityList"
                  placeholder="请选择"
                  clearable
                  style="width: 120px;"
                >
                  <el-option
                    style="width: 120px;"
                    v-for="(province,index) in provinceList"
                    :key="index"
                    :label="province"
                    :value="province"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="地区：">
                <el-select
                  v-model="companyForm.city"
                  placeholder="请选择"
                  clearable
                  style="width: 120px;"
                  :disabled="isCity || companyForm.city == null"
                >
                  <el-option
                    style="width: 120px;"
                    v-for="(city,index) in cityList"
                    :key="index"
                    :label="city"
                    :value="city"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="企业简称：">
                <el-input
                  v-model.trim="companyForm.shortName"
                  placeholder="请输入"
                  clearable
                  @keyup.enter.native="searchForm"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="状态：">
                <el-select v-model="companyForm.state" placeholder="请选择" style="width: 120px;">
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item class="searchBtn">
                <el-button type="primary" size="small" @click="searchForm">搜索</el-button>
                <el-button size="small" @click="clearForm">清除</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: right;" class="searchBtn">
              <el-form-item>
                <el-button
                  size="small"
                  style="margin-left: 10px;"
                  type="success"
                  icon="el-icon-edit"
                  @click="addDialogFormVisible = true"
                >新增用户</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 记录展示 -->
        <el-alert type="info" show-icon :closable="false">共{{count}}条记录</el-alert>
        <br />
        <!-- 表格区域 -->
        <el-table
          :data="tableData"
          stripe
          style="width: 100%;"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <el-table-column align="center" prop="id" label="序号"></el-table-column>
          <el-table-column align="center" prop="number" label="企业编号"></el-table-column>
          <el-table-column align="center" prop="shortName" label="企业简介"></el-table-column>
          <el-table-column align="center" prop="tags" label="标签"></el-table-column>
          <el-table-column align="center" prop="creatorID" label="创建者"></el-table-column>
          <el-table-column align="center" prop="addDate" label="创建日期"></el-table-column>
          <el-table-column align="center" prop="remarks" label="备注"></el-table-column>
          <el-table-column align="center" label="状态">
            <template slot-scope="scope">{{scope.row.state===1?'启用':'禁用'}}</template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  plain
                  title="编辑"
                  @click="updateCompanyDetail(scope.row)"
                ></el-button>
              </el-tooltip>
              <!-- 禁用按钮 -->
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.state===1?'禁用':'启用'"
                placement="top"
              >
                <el-button
                  @click="isDisableState($event,scope.row)"
                  :type="scope.row.state===1?'warning':'success'"
                  :icon="scope.row.state===1?'el-icon-close':'el-icon-check'"
                  circle
                  plain
                ></el-button>
              </el-tooltip>
              <!-- 删除按钮 -->
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  plain
                  @click="deleteCompany($event,scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <br />

        <!-- 弹层（新增） -->
        <CompanysAdd
          v-if="addDialogFormVisible"
          :visible.sync="addDialogFormVisible"
          @getEvent="getEvent"
        ></CompanysAdd>

        <!-- 弹层（编辑） -->
        <CompanyUpdate
          v-if="updateDialogFormVisible"
          :visible.sync="updateDialogFormVisible"
          :companyDetail="companyDetail"
          @getEvent="getEvent"
        ></CompanyUpdate>

        <!-- 分页 -->
        <div class="block">
          <el-pagination
            style="text-align:right;margin-top:20px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="companyForm.page"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="companyForm.pagesize"
            layout="total,prev, pager, next, sizes,  jumper"
            :total="count"
            background
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list, disabled, remove, detail } from '../../api/hmmm/companys'
import { provinces, citys } from '../../api/hmmm/citys.js'
import dayjs from 'dayjs'
import CompanysAdd from '../components/companys-add'
import CompanyUpdate from '../components/companys-update.vue'
export default {
  name: 'CompanysList',
  components: {
    CompanysAdd,
    CompanyUpdate
  },
  data () {
    return {
      // 获取企业列表的请求参数
      companyForm: {
        page: 1, // 当前页数
        pagesize: 10, // 页尺寸,每页显示多少数据
        tags: '',// 标签名称
        province: '',// 企业所在地省份
        city: '',// 企业所在城市
        shortName: '',// 企业简称
        state: null//状态
      },
      tableData: [], //企业列表
      count: 0,//总的数据条数
      loading: true,//是否开始加载状态
      provinceList: [],//城市列表
      cityList: [],//每个城市所关联的区域列表
      isCity: true,//是否禁用区域按钮
      addDialogFormVisible: false,//控制弹层（新增）
      updateDialogFormVisible: false,//控制弹层（编辑）
      companyDetail: {}
    }
  },
  created () {
    this.getprovinceList()
    // 获取表格数据
    this.getCompanyList()
  },
  methods: {
    // 获取表格中的数据（企业列表）
    async getCompanyList () {
      try {
        const { data } = await list(this.companyForm)
        data.items.forEach(item => {
          item.addDate = dayjs(item.addDate).format('YYYY-MM-DD')
        })
        this.tableData = data.items
        this.count = data.counts
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false
      }
    },
    //分页
    //每页以第几条数据显示
    handleSizeChange (pagesize) {
      this.companyForm.pagesize = pagesize
      this.getCompanyList()
    },
    //显示当前是第几页
    handleCurrentChange (page) {
      this.companyForm.page = page
      this.getCompanyList()
    },
    // 获取搜索栏中的城市列表
    getprovinceList () {
      this.provinceList = provinces()
    },
    //获取城市所关联的区域列表
    getCityList () {
      this.isCity = false
      this.cityList = citys(this.companyForm.province)
      this.companyForm.city = this.cityList[0]
    },
    //搜索表单的数据
    searchForm () {
      this.getCompanyList()
    },
    //清除表单数据
    clearForm () {
      this.companyForm.page = 1
      this.companyForm.pagesize = 10
      this.companyForm.tags = ''
      this.companyForm.province = ''
      this.companyForm.city = ''
      this.companyForm.shortName = ''
      this.companyForm.state = null
      this.isCity = true
      this.getCompanyList()
    },
    //是否禁用
    isDisableState (e, row) {
      this.$confirm(`此条记录是否${row.state === 1 ? '禁用' : '启动'}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          if (row.state === 1) {
            row.state = 0
          } else {
            row.state = 1
          }
          console.log(row.state);
          await disabled(row)
          if (row.state === 1) {
            this.$message.success('启动成功!')
          } else {
            this.$message.success('禁用成功!')
          }
          this.getCompanyList()
        } catch (error) {
          this.$message.error('操作失败!')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      })
      //调用失去焦点的方法
      this.forceBtnBlur(e)
    },
    //删除表格中的数据
    deleteCompany (e, row) {
      this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await remove(row)
          this.getCompanyList()
          this.$message.success('删除成功!')
        } catch (error) {
          this.$message.error('删除失败!')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
      //调用失去焦点的方法
      this.forceBtnBlur(e)
    },

    // 强制el-button点击后失焦(传$event)
    forceBtnBlur (e) {
      let target = e.target;
      if (target.nodeName == 'SPAN' || target.nodeName == 'I') {
        target = e.target.parentNode;
      }
      target.blur();
    },
    //添加后重新渲染页面
    getEvent () {
      this.getCompanyList()
    },
    async updateCompanyDetail (row) {
      const { data } = await detail(row)
      this.companyDetail = data
      this.updateDialogFormVisible = true
    }
  }
}

</script>

<style scoped>
.searchBtn {
  margin-top: 33px;
}
</style>
